import {
  Action,
  getModule,
  Module,
  Mutation,
  VuexModule,
} from "vuex-module-decorators";
import store from "@/store";
import { IUserState } from "@/@types/store";

import imgUrl from "@/assets/img_avatar_example.gif";
import Cookies from "js-cookie";
import router, { resetRouter } from "@/router";
@Module({ dynamic: true, namespaced: true, store: store, name: "user" })
export default class UserStore extends VuexModule implements IUserState {
  public avatar: string = this.getLocalUserInfo.avatar || imgUrl;
  public roleId: string = this.getLocalUserInfo.roleId || "";
  public roles: string[] = this.getLocalUserInfo.roles || [];
  public token: string = this.getLocalUserInfo.token || "";
  public userId: string = this.getLocalUserInfo.userId || "";
  public userName: string = this.getLocalUserInfo.userName || "";
  public userNickName: string = this.getLocalUserInfo.userNickName || "";

  //#region getter =================================
  public get getAvatar() {
    return this.avatar;
  }
  public get getUserName() {
    return this.userName;
  }
  public get getNickName() {
    return this.userNickName;
  }
  public get getRoles() {
    return this.roles;
  }
  private get getLocalUserInfo() {
    const userInfoString = localStorage.getItem("userInfo");
    const userInfo = JSON.parse(userInfoString || "{}");
    return userInfo;
  }
  //#endregion

  @Action
  public saveUserInfo(userInfo: any) {
    return new Promise((resolve, reject) => {
      try {
        this.context.commit("SAVE_USER_INFO", userInfo);
        resolve("success");
      } catch (error) {
        reject(error);
      }
    });
  }
  @Action
  logout() {
    return new Promise((resolve, reject) => {
      try {
        // this.context.dispatch("router/delAllRoute", null, { root: true });
        this.context.commit("LOGOUT");
        router.replace({ name: "login" });
        resolve("success");
      } catch (error) {
        reject(error);
      }
    });
  }

  @Mutation
  private SAVE_USER_INFO(userInfo) {
    this.userId = userInfo.userId;
    this.userName = userInfo.userName;
    this.userNickName = userInfo.userNickName;
    // this.avatar = userInfo.avatar;
    this.roleId = userInfo.roleId;
    this.roles = userInfo.roles;
    this.token = userInfo.token;
    localStorage.setItem("userInfo", JSON.stringify(userInfo));
    Cookies.set("admin-token", userInfo.token, {
      expires: 1 * 24 * 60 * 60,
    });
  }

  @Mutation
  private LOGOUT() {
    // 这里只是在本地模拟删除了用户信息，在真实场景下需要 调后台登出接口 来真正实现登出功能
    this.userId = "";
    this.userName = "";
    this.userNickName = "";
    this.roleId = "";
    this.roles = [];
    this.avatar = "";
    this.token = "";
    resetRouter();
    Cookies.remove("admin-token");
    localStorage.removeItem("userInfo");
  }
}
export const UserStoreModule = getModule(UserStore, store);
// UserStoreModule.getAvatar;
